import { Modal, Form, Input } from 'antd'
import { toWei } from '../utils'


export default function BalanceForm({ open, hideModal }) {
  const [form] = Form.useForm()
  const onFinish = (val) => {
    const { account, exchange, token, ethAddress } = window.web
    
    const map = {
      // 充值以太币
      '1': async () => {
        await exchange.methods.depositEther().send({
          from: account,
          value: toWei(val.amount)
        })
      },
      // 提现以太币
      '2': async () => {
        await exchange.methods.withdrawEther(toWei(val.amount)).send({
          from: account
        })
      },
      // 充值 min 币
      '3': async () => {
        await token.methods.approve(exchange.options.address, toWei(val.amount)).send({
          from: account
        })
        await exchange.methods.depositToken(token.options.address, toWei(val.amount)).send({
          from: account
        })
      },
      // 提现 min 币
      '4': async () => {
        await exchange.methods.withdrawToken(token.options.address, toWei(val.amount)).send({
          from: account
        })
      }
    }
    map[open.type]()
    form.resetFields()
    hideModal()
  }

  const onOk = () => {
    form.submit()
  }
  
  return (
    <>
      <Modal
        title={ open.title }
        open={ open.value }
        onCancel={ hideModal }
        onOk={ onOk }
      >
        <Form
          form={ form }
          onFinish={onFinish }
          initialValues={{
            amount: '0'
          }}
        >
          <Form.Item name='amount' label={ open.title } rules={ [ 
            {
              required: true
            }
           ]}>
            <Input></Input>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}